package cc.fs.study.pinyin;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * RecyclerView滑动到某个固定位置
 * Created by fostion on 6/6/16.
 */
public class ScrollRecyclerViewHelper {

    private boolean move = false;
    private int mIndex = -1;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLinearLayoutManager;

    public ScrollRecyclerViewHelper(RecyclerView recyclerView) {
        if (recyclerView == null) throw new NullPointerException("recyclerView not null");
        if (!(recyclerView.getLayoutManager() instanceof LinearLayoutManager))
            throw new IllegalStateException("recyclerView layoutManager must be linearLayoutManager");

        this.recyclerView = recyclerView;
        this.mLinearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        this.recyclerView.addOnScrollListener(new RecyclerViewListener());
    }

    /**
     * 滑动处理
     */
    public void moveToPosition(int _mIndex) {
        this.mIndex = _mIndex;
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (mIndex <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            recyclerView.scrollToPosition(mIndex);
        } else if (mIndex <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = recyclerView.getChildAt(mIndex - firstItem).getTop();
            recyclerView.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            recyclerView.scrollToPosition(mIndex);
            //这里这个变量是用在RecyclerView滚动监听里面的
            move = true;
        }
    }

    /**
     * 滑动处理将tab滑动首个位置
     */
    class RecyclerViewListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (move) {
                move = false;
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < recyclerView.getChildCount()) {
                    int top = recyclerView.getChildAt(n).getTop();
                    recyclerView.scrollBy(0, top);
                }
            }
        }
    }

}
